import tkinter
import tkinter.filedialog
import tkinter.messagebox
import os
from PIL import ImageGrab,ImageGrab
from time import sleep

#创建tkinter应用程序，设置窗口大小和位置，不允许改变窗口大小
root = tkinter.Tk()
root.geometry("100x40+400+300")
root.resizable(False, False)

class MyCapture:
   def __init__(self,png):
     #变量X和Y用于记录鼠标左键按下的位置
     self.X = tkinter.IntVar(value=0)
     self.Y = tkinter.IntVar(value=0)

     #屏幕尺寸
     screenWidth = root.winfo_screenwidth()
     screenHeight = root.winfo_screenheight()

     #创建顶级组件窗口
     self.top = tkinter.Toplevel(root, width=screenWidth, height=screenHeight)
     #不显示最大化，最小化按钮
     self.top.overrideredirect(True)
     self.canvas = tkinter.Canvas(self.top, bg='white', width=screenWidth, height=screenHeight)
     #显示全屏截图，在全屏截图上进行区域截图
     self.image = tkinter.PhotoImage(file=png)
     self.canvas.create_image(screenWidth/2, screenHeight/2, image=self.image)

     #获取鼠标左键抬起的位置，取色，并转换成合适的颜色格式进行显示
     def onLeftButtonDown(event):
       im = Image.open(png)
       color = im.getpixel((event.x, event.y))[:3]
       msg = str(color) + '\n'
       color = '#' + ''.join(map(lambda x:hex(x)[2:], color))
       msg += color
       tkinter.messagebox.showinfo('', msg)

       #关闭当前窗口
       self.top.destroy()
     self.canvas.bind('<ButtonRelease-1>', onLeftButtonUp)

     self.canvas.pack(fill=tkinter.BOTH, expand=tkinter.YES)

#开始截图
def buttonCaptureClick():
  #最小化主窗口
  root.state('icon')
  sleep(0.2)

  filename = 'temp.png'
  im = ImageGrab.grab()
  im.save(filename)
  im.close()

  #显示全屏幕截图
  w = MyCapture(filename)
  buttonCapture.wait_window(w.top)
  
  root.state('normal')
  os.remove(filename)
buttonCapture = tkinter.Button(root, 
                    text='取色',
                     command=buttonCaptureClick)
buttonCapture.place(x=10, y=10,width=80, height=20)

#启动消息主循环
root.mainloop()